package com.example.demo.controller.user;

import com.example.demo.bean.ErrorCode;
import com.example.demo.bean.JsonData;
import com.example.demo.bean.RegisterBean;
import com.example.demo.bean.ThisSystemException;
import com.example.demo.bean.request.LoginRequest;
import com.example.demo.bean.response.LoginResponse;
import com.example.demo.repository.Open;
import com.example.demo.repository.UserRepository;
import com.example.demo.table.UserTable;
import com.example.demo.utli.Ove;
import com.example.demo.utli.PhoneNumberUtil;
import com.example.demo.utli.RedisUtil;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import static com.example.demo.bean.ThisSystemUtil.$;
import static com.example.demo.utli.PwdUtil.judgePassWord;

/**
 * 费浩东
 * 2018/11/2
 * Created by fhd
 */
@RestController
@Api(description = "注册" )
@RequestMapping(value = "/user")
public class RegisterController {

    @Autowired
    UserRepository mUserRepository;

    @Autowired
    RedisUtil mRedisUtil;

    @Open
    @PostMapping(value = "register")
//    @ApiOperation(value="注册", notes="填入注册信息")
//    @ApiImplicitParam(name = "RequestBody", value = "loginRequest", required = true, dataType = "Integer", paramType = "path")
    public JsonData register(@Valid @RequestBody RegisterBean registerBean) {

        String userName = $("用户名不能为空", registerBean.getUserName());
        PhoneNumberUtil.isPhone(userName);//检验用户名是否为手机号

        String password = $("密码不能为空", registerBean.getPassword());

        String confirm = $("确认密码不能为空", registerBean.getConfirmPassword());

        String smsCode = $("验证码不能为空", registerBean.getSmsCode());

        //TODO 暂未判别验证码可用性

        judgePassWord(password,confirm);

        long gen_time = System.currentTimeMillis();
        Date date = new Date(gen_time);
        UserTable userTable = new UserTable(userName,Ove.encryption(password, userName) , date, date);

        UserTable user = mUserRepository.findByUserName(userName);
        if (null != user) {
            throw new ThisSystemException(ErrorCode.ACCOUNT_EXISTENCE.getText(),ErrorCode.ACCOUNT_EXISTENCE.getStatus());
        }
        mUserRepository.save(userTable);

        return JsonData.success("注册成功");
    }

}
